import Cookies from 'js-cookie'

const view = {
    namespaced: true,
    state:{
        sidebar:{
            opened: Cookies.get('sidebarStatus')?(!!+Cookies.get('sidebarStatus')):true,
            withoutAnimation:false
        },
        visitedViews:[],
        cachedViews:[]
    },
    mutations:{
        TOGGLE_SIDEBAR: state => {
            state.sidebar.opened = !state.sidebar.opened
            state.sidebar.withoutAnimation = false
            if (state.sidebar.opened) {
                Cookies.set('sidebarStatus', 1)
            } else {
                Cookies.set('sidebarStatus', 0)
            }
        },
        ADD_VISITED_VIEW:(state, view)=>{
            if(state.visitedViews.some(v=>v.path==view.path)) return 
            state.visitedViews.push(
                Object.assign({}, view, {
                    name:view.meta.name
                })
            )
        },
        DEL_VISITED_VIEW:(state,view) => {
            for(const [i, v] of state.visitedViews.entries()){
                if(v.path === view.path){
                    state.visitedViews.splice(i, 1)
                    break
                }
            }
        },
        DEL_ALL_VISITED_VIEWS:(state)=>{
            const affixTags = state.visitedViews.filter(tag => tag.meta.affix)
            state.visitedViews = affixTags
        }
    },
    actions:{
        toggleSideBar({ commit }) {
            commit('TOGGLE_SIDEBAR')
        },
        addView({dispatch}, view){
            dispatch('addVisitedView', view)
        },
        addVisitedView({commit}, view){
            commit('ADD_VISITED_VIEW', view)
        },
        delView({dispatch, state}, view){
            return new Promise((resolve, reject)=>{
                dispatch('delVisitedView', view)
                resolve({
                    visitedViews:[...state.visitedViews],
                })
            })
        },
        delVisitedView({commit, state}, view){
            return new Promise((resolve)=>{
                commit('DEL_VISITED_VIEW', view)
                resolve([...state.visitedViews])
            })
        },  
        delAllViews({dispatch, state}, view){
            return new Promise(resolve=>{
                dispatch('delAllVisitedViews', view)

                resolve({
                    visitedViews:[...state.visitedViews],
                })
            })
        },
        delAllVisitedViews({commit, state}){
            return new Promise(resolve => {
                commit('DEL_ALL_VISITED_VIEWS')
                resolve([...state.visitedViews])
            })
        }
    }
}

export default view